$(function () {
    var content_ = "";
    var $search = parseSearch(),
        data = {}, arg = ''
    config = {
        queryAccount: '/payType/query?type=2',// // 供货地账户
    };
    arg = data[$search.type];

    // initSelect();

    if (!!$search.id) {
        $.get('/info/get?id=' + $search.id, function (res) {
            var offer = res.data;
            debugger;
            $('[name=title]').val(offer.title);
            $('[name=summary]').val(offer.summary);
        })
        initBtn();
    } else {
        initSelectPicker();
        initBtn();
    }

    /**
     *
     */
    function initBtn() {


        onClick($('.video-upload'), function () {
            var self = this;
            uploadFn('上传视频', {
                w: 500,
                h: 500,
                plain: true,
                num: 12,
                labelNum: '12 upload-custom-label',
                noCrop: false,
                preview: 'left-top-preview'
            }, function (data,file) {
                $('[name=video]').val(data.data.path)
                file.currentFileSize = file.data.currentFileSize
                    $('[name=video]').siblings('div').html('<a target="_blank" href="'+data.data.path+'">预览视频['+bytesToSize(file.currentFileSize||0)+']</a>')
                closeLayer(data.layerIndex);
            });
        })
        onClick($('.video-img-upload'), function () {
            var self = this;//
            uploadFn('上传预览图', {
                w: 500,
                h: 500,
                plain: true,
                num: 12,
                labelNum: '12 upload-custom-label',
                noCrop: false,
                preview: 'left-top-preview'
            }, function (data) {
                $('.video-img-upload').find('img').attr('src', data.data.path)
                $('[name=video-preview]').val(data.data.path)
                closeLayer(data.layerIndex);
            });
        })

    }

    function initSelectPicker(opt) {
        opt = opt || {};
        $.when(
            $.get('/category/list?type1=kepu-video-category&level=1&size=' + maxSize)
        ).then(function (category) {
            category = category.list;
            window.categoryId = _.groupBy(category, 'id');
            //
            var $categoryId = $('[name=categoryId]');
            if (!$categoryId.find('option').length) {
                category.map(function (item, index) {
                    $categoryId.append('<option value="' + item.id + '">' + item.name + '</option>')
                });
            } //帮忙运营一个
            ///
            $('.slid-bars')
                .find('[name="categoryId"]')
                .selectpicker({liveSearch: true,})
                .change(function (e) {
                })
                .end();
            if (opt.categoryId) {
                $('[name="categoryId"]').selectpicker('val', opt.categoryId);
            }
        })
    }

    function submit(status) {
        if ($('.image-cover-crop').length) {
            if (!confirm('您还有上传后未裁剪的图片，是否确认提交？')) {
                return;
            }
        }
        var form = {status: status || '0'};
        form.title = $('[name=title]').val();
        if (!form.title) {
            return fnFail('请填写视频标题');
        }
        form.type1 = 31;
        form.summary = $('[name=summary]').val();
        if (!form.summary) {
            return fnFail('请填写视频简介');
        }
        if ($('[name=categoryId]').val()) {
            form.categoryId = $('[name=categoryId]').val();
        } else {
            return fnFail('请选择分类')
        }

        var $video = $('[name=video]');
        form.video = $video.val() || form.video || '';
        var $preview = $('[name=video-preview]');//兄弟
        form.thumbnail = $preview.val() || form.thumbnail || '';
        $.post(!!$search.id ? "/info/update" : "/info/create", form, function (res) {
            if (res.code == 200) {
                if ('1' == status && form.id) {
                    fnSuccess('保存成功');
                } else {
                    alert('保存成功');
                }
                window.location = './index.html?type=kepu-video'
            } else {
                return fnFail(res.error || '保存失败');
            }
        })
    }

    onClick($('.btn-up'), function () {
        submit(1)
    })

    /**
     * 保存植物
     */
    onClick($('.btn-save'), function () {
        submit(0);////
    })

    function upload(lab, ratio) {
        ratio = ratio || {};
        dialogForm({
            title: '上传' + lab,
            fullScreen: true,
            data: [

                {
                    type: 'upload-dialog',
                    label: lab,
                    require: true, // 是否必填
                    name: 'upload',
                    labelStyle: ratio.style || '',
                    value: '',

                    num: 8,
                    labelNum: 2,
                    validate: 'ipt  validate[required]',
                    btnClass: 'select-file',
                    btn: {
                        class_: '9 col-xs-offset-1'
                    }
                },
            ],
            shown: function (obj) {
                $('.select-file').$upload({
                    w: ratio.w || 185,
                    h: ratio.h || 164,

                    submit: function (path) {
                        closeLayer(obj.index);
                        $('.preview').attr('src', path);
                    }
                })
            },
            noForm: true,
            submit: function (data) {
            }
        });
    }

    var self = this;

    function genForm() {
        dialogForm({
            eleId: 'form',
            title: '',
            data: arg.data,
            shown: arg.shown || function () {
            },
            submit: function (data) {
                data.img = $('.preview').attr('src');
                var url = arg.add;
                if ($search.id) {
                    data.id = $search.id;
                    url = arg.update;
                }
                if (data.editorValue) {
                    data.profile = data.editorValue
                }
                if (arg.reform) {
                    data = arg.reform(data);
                }
                $.post(url, data, function (res) {
                    if (res.code == 200) {
                        fnSuccess('操作成功！');
                        window.location.href = './index.html?type=' + $search.type
                    } else {
                        fnFail(res.error || '操作失败！')
                    }
                });
            }
        }, true);
    }


    /**
     * 富文本编辑器
     * @param id
     */
    function initEditor(id, content, opt) {
        opt = opt || {};
        window.editor = UE.getEditor(id, {
            //工具栏
            toolbars: [[
                'Source',
                'fullscreen', 'undo', 'redo', '|',
                'bold', 'italic', 'underline', 'strikethrough', , 'removeformat', 'formatmatch',
                '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', '|',
                'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'link', 'unlink', '|',
                'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|', 'indent', '|',
                'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
                'insertframe', '|',
                'imagenone', 'imageleft', 'imageright', 'imagecenter', '|', 'simpleupload',
                'horizontal', 'insertvideo'
                // ,'preview'
            ]],
            lang: "zh-cn",//字体
            fontfamily: [
                {label: '', name: 'songti', val: '宋体,SimSun'},
                {label: '', name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
                {label: '', name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
                {label: '', name: 'heiti', val: '黑体, SimHei'},
                {label: '', name: 'lishu', val: '隶书, SimLi'},
                {label: '', name: 'andaleMono', val: 'andale mono'},
                {label: '', name: 'arial', val: 'arial, helvetica,sans-serif'},
                {label: '', name: 'arialBlack', val: 'arial black,avant garde'},
                {label: '', name: 'comicSansMs', val: 'comic sans ms'},
                {label: '', name: 'impact', val: 'impact,chicago'},
                {label: '', name: 'timesNewRoman', val: 'times new roman'}
            ],//字号
            'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36],
            enableAutoSave: true,
            autoHeightEnabled: true,
            initialFrameHeight: '400px',
            initialFrameWidth: '100%',
            readonly: false,
            initialFrameHeight: 'auto',
            whitList: {
                a: ['target', 'href', 'title', 'class', 'style'],
                abbr: ['title', 'class', 'style'],
                address: ['class', 'style'],
                area: ['shape', 'coords', 'href', 'alt'],
                article: [],
                aside: [],
                audio: ['autoplay', 'controls', 'loop', 'preload', 'src', 'class', 'style'],
                b: ['class', 'style'],
                bdi: ['dir'],
                bdo: ['dir'],
                big: [],
                blockquote: ['cite', 'class', 'style'],
                br: [],
                caption: ['class', 'style'],
                center: [],
                cite: [],
                code: ['class', 'style'],
                col: ['align', 'valign', 'span', 'width', 'class', 'style'],
                colgroup: ['align', 'valign', 'span', 'width', 'class', 'style'],
                dd: ['class', 'style'],
                del: ['datetime'],
                details: ['open'],
                div: ['class', 'style'],
                dl: ['class', 'style'],
                dt: ['class', 'style'],
                em: ['class', 'style'],
                font: ['color', 'size', 'face'],
                footer: [],
                h1: ['class', 'style'],
                h2: ['class', 'style'],
                h3: ['class', 'style'],
                h4: ['class', 'style'],
                h5: ['class', 'style'],
                h6: ['class', 'style'],
                header: [],
                hr: [],
                i: ['class', 'style'],
                img: ['src', 'alt', 'title', 'width', 'height', 'id', '_src', '_url', 'loadingclass', 'class', 'data-latex'],
                ins: ['datetime'],
                li: ['class', 'style'],
                mark: [],
                nav: [],
                ol: ['class', 'style'],
                p: ['class', 'style'],
                pre: ['class', 'style'],
                s: [],
                section: [],
                small: [],
                span: ['class', 'style'],
                sub: ['class', 'style'],
                sup: ['class', 'style'],
                strong: ['class', 'style'],
                table: ['width', 'border', 'align', 'valign', 'class', 'style'],
                tbody: ['align', 'valign', 'class', 'style'],
                td: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'],
                tfoot: ['align', 'valign', 'class', 'style'],
                th: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'],
                thead: ['align', 'valign', 'class', 'style'],
                tr: ['rowspan', 'align', 'valign', 'class', 'style'],
                tt: [],
                u: [],
                ul: ['class', 'style'],
                video: ['autoplay', 'controls', 'loop', 'preload', 'src', 'height', 'width', 'class', 'style'],
                source: ['src', 'type'],
                // embed:['type','class','pluginspage','src','wdith','height','align','style','wmode','play','autoplay',
                //     'loop','menu','allowsscriptaccess','allowfullscreen','controls','preload'
                // ],
                iframe: ['src', 'class', 'height', 'width', 'max-width', 'max-height', 'align',
                    'frameborder', 'allowfullscreen'
                ]
            }
        });
        window.editor.ready(function (ueditor) {

            if (opt && opt.source) { // 源码模式
                setTimeout(function () {
                    if (window.editor.queryCommandState('source') != 1) {//判断编辑模式状态:0表示【源代码】HTML视图；1是【设计】视图,即可见即所得；-1表示不可用
                        window.editor.execCommand('source'); //切换到【设计】视图
                    }
                }, 500);
            }
            if (content) {
                window.editor.setContent(content);
            }

        });

        window.editor.addListener('contentChange', function (editor_) {
            var self = this;
            content_ = self.getContent();
        });
    }

});